package com.boang.dao;

import com.boang.po.Student;
import com.boang.util.DBUtil;

import javax.swing.plaf.SeparatorUI;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
  @author: 13813
  @date: 2024/7/12 16:16
*/
public class StudentDaoImpl implements StudentDao {
    @Override
    public Student selectStuById(int id) {
        Connection conn = null;
        try {
            conn = DBUtil.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement("select * from student where id = ?");
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            Student student = null;
            while (resultSet.next()) {
                int stuId = resultSet.getInt("id");
                String name = resultSet.getString("name");
                student = new Student(stuId, name);
            }
            return student;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Student> selectStuList() {
        Connection conn = null;
        try {
            conn = DBUtil.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement("select * from student");
            ResultSet resultSet = preparedStatement.executeQuery();
            ArrayList<Student> list = new ArrayList<>();
            while (resultSet.next()) {
                int stuId = resultSet.getInt("id");
                String name = resultSet.getString("name");
                Student student = new Student(stuId, name);
                list.add(student);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
